﻿using System;
using System.Diagnostics;
using System.IO;
using Ionic.Zip;
using octalforty.Chinchillin.Shared.Deployment;
using octalforty.Chinchillin.Shared.Deployment.Metadata;
using octalforty.Chinchillin.Shared.Deployment.Resources;

namespace octalforty.Chinchillin.Actions.Fs
{
    /// <summary>
    /// Pepresents an action which, when executed, restores specified directory.
    /// </summary>
    [Action(Name)]
    public class RestoreDirectoryAction : ActionBase
    {
        #region Private Constants
        private const string Name = "restore-directory";
        private const string Location = "location";
        private const string BackupLocation = "backup-location";
        private const string BackupResource = "backup-resource";

        private static readonly ActionInfo actionInfo = new ActionInfo
                                                            {
                                                                Name = Name,
                                                                Arguments = new[]
                                                                                {
                                                                                    new ActionArgumentInfo(Location, ActionArgumentType.Uri),
                                                                                    new ActionArgumentInfo(BackupLocation, ActionArgumentType.Uri),
                                                                                    new ActionArgumentInfo(BackupResource, ActionArgumentType.Uri)
                                                                                }
                                                            };
        #endregion

        public IResourceProvider ResourceProvider
        { get; set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="RestoreDirectoryAction"/> class.
        /// </summary>
        public RestoreDirectoryAction() :
            base(actionInfo)
        {
        }

        public override void Execute(IActionExecutionContext executionContext)
        {
            var location = (Uri)executionContext.Arguments[Location];
            try
            {
                Restore(executionContext, location);
            }
            catch(Exception e)
            {
                TracingManager.TraceEvent(executionContext, TraceEventType.Error, 0, e.ToString());
            }
        }

        private void Restore(IActionExecutionContext executionContext, Uri location)
        {
            //
            // If "backup-location" is specified, we're restoring from a directory
            if(executionContext.Arguments.ContainsKey(BackupLocation))
            {
                var backupLocation = (Uri)executionContext.Arguments[BackupLocation];

                /*var syncManager = new SyncManager<string, string>(
                    new DelegateSyncCallback<string, string>());
                syncManager.SyncOneWay()
                 * */

                TracingManager.TraceEvent(executionContext, TraceEventType.Information, 0, string.Format("Restoring '{0}' from '{1}'", location, backupLocation));

                //
                // TODO: Replace with SyncManager so that no unneccessary file IO is performed?
                CopyDirectory(backupLocation.LocalPath, location.LocalPath,
                              (s, t) => TracingManager.TraceEvent(executionContext, TraceEventType.Verbose, 0, string.Format("Restoring '{0}' to '{1}'", s, t)));

                TracingManager.TraceEvent(executionContext, TraceEventType.Information, 0, string.Format("Restored '{0}' from '{1}'", location, backupLocation));
            } // if
            else if(executionContext.Arguments.ContainsKey(BackupResource))
            {
                var backupResource = (Uri)executionContext.Arguments[BackupResource];

                TracingManager.TraceEvent(executionContext, TraceEventType.Information, 0, string.Format("Restoring '{0}' from '{1}'", location, backupResource));

                using(var zipFile = new ZipFile(backupResource.AbsolutePath))
                {
                    zipFile.ExtractAll(location.AbsolutePath, ExtractExistingFileAction.OverwriteSilently);
                } // using

                TracingManager.TraceEvent(executionContext, TraceEventType.Information, 0, string.Format("Restored '{0}' from '{1}'", location, backupResource));
            } // else if
        }

        public static void CopyDirectory(string sourceDirectory, string targetDirectory, Action<string, string> fileCopyCallback)
        {
            if(!Directory.Exists(targetDirectory))
                Directory.CreateDirectory(targetDirectory);

            var files = Directory.GetFiles(sourceDirectory);

            foreach(var file in files)
            {
                var name = Path.GetFileName(file);
                var dest = Path.Combine(targetDirectory, name);

                File.Copy(file, dest, true);

                if(fileCopyCallback != null)
                    fileCopyCallback(file, dest);
            }

            var folders = Directory.GetDirectories(sourceDirectory);

            foreach(var folder in folders)
            {
                var name = Path.GetFileName(folder);
                var dest = Path.Combine(targetDirectory, name);

                CopyDirectory(folder, dest, fileCopyCallback);
            }
        }
    }
}